<?php

namespace app\common\model;

use helper\Form;

class ConfigModel extends BaseModel
{

  protected $table = 'config';

  // 设置json类型字段
  protected $json = [];

  // 设置JSON数据返回数组
  protected $jsonAssoc = true;

  /**
   * 刷新缓存
   * @return array
   */
  public function refreshCache()
  {
    $webConfig = $this->column('config_value', 'config_key');
    cache('web_config', $webConfig);
    return $webConfig;
  }

  /**
   * 添加
   * @param $data
   * @return ConfigModel|\think\Model
   * @throws \Exception
   */
  public function add($data)
  {
    $info = $this->where('config_key', $data['config_key'])->find();
    if ($info) abort(500, '已存在该字段标识');
    return self::create($data);
  }

  /**
   * 编辑
   * @param $data
   * @return ConfigModel
   */
  public function edit($data)
  {
    return self::update($data);
  }

  /**
   * 删除
   * @param $id
   * @return bool
   * @throws \Exception
   */
  public function del($id)
  {
    return $this->where('id', $id)->delete();
  }

  /**
   * 获取表单数据
   * @param string $group
   * @return array
   * @throws \Exception
   */
  public function getForm($group = 'site')
  {
    $list = $this->where('config_group', $group)->order('show_order asc')->select();
    $h = [];
    foreach ($list as $v) {
      $fun = $v['config_type'];
      $options = empty($v['config_set']) ? [] : json_decode(html_out($v['config_set']), true);
      $form = Form::$fun("config[{$v['config_key']}]", $v['config_value'], $options);
      $h[] = <<<EOT
<div class="form-group">
    <label class="col-sm-2 control-label">{$v['config_title']}</label>
    <div class="col-sm-8">
      {$form}
      <small class="help-block">{$v['config_description']}</small>
    </div>
    <div class="col-sm-2">
        <div class="pull-right">
          <button type="button" class="btn btn-default btn-sm" onclick="doAction.edit({$v['id']})"><i class="mdi mdi-pencil"></i> </button>
          <button type="button" class="btn btn-default btn-sm" onclick="doAction.del({$v['id']})"><i class="mdi mdi-archive"></i> </button>
        </div>
    </div>
</div>
EOT;
    }
    return $h;
  }
}
